package br.com.affero.testewel.model.document;

import java.util.Date;
import java.util.List;


import org.hibernate.Session;
import org.hibernate.Transaction;

import br.com.affero.testewel.util.HibernateUtil;

/**
 * Implementação dos Serviços de Persistência dos Modelos
 * Utilizando o Hibernate como abstração objeto relacional para persistência em SBGD.
 * 
 * @author Welington Veiga
 * @since 20/12/2011
 */
public class DocumentHibernateDAO implements DocumentDAO {

	private final String SQL_FIND_ALL = "SELECT d FROM Document d";
	
	
	@Override
	public void persist(Document document) {
		final Session session = HibernateUtil.getInstance().getSession();
		Transaction tx = session.beginTransaction();
		try{
			if(document.getId() != null)
				session.persist(document);
			else{
				session.save(document);
			}
			tx.commit();
		}catch (Exception e) {
			tx.rollback();
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Document> listAll() {
		final Session session = HibernateUtil.getInstance().getSession();
		return session.createQuery(SQL_FIND_ALL).list();
	}

	@Override
	public Document findOneById(Long id) {
		final Session session = HibernateUtil.getInstance().getSession();
		return (Document) session.get(Document.class, id);
	}

	@Override
	public void delete(Document document) {
		final Session session = HibernateUtil.getInstance().getSession();
		Transaction tx = session.beginTransaction();
		try{
			session.delete(document);
			tx.commit();
		}catch (Exception e) {
			tx.rollback();
		}
		
	}

}
